package com.xiguthings.xiniu.iot.post.common;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class HttpUtils {

    public static final String RESPONSE_CODE = "responseCode";
    public static final String RESPONSE_BODY = "responseBody";

    /**
     * @param urlStr
     * @param params
     * @param needResult 是否需要返回的结果（响应体部分）
     * @return
     * @throws IOException
     */
    public static Map<String, Object> post(String urlStr, byte[] params, boolean needResult) throws IOException {
        Map<String, Object> resMap = new HashMap<>();

        URL url = new URL(urlStr);
        HttpURLConnection http = (HttpURLConnection) url.openConnection();
        http.setRequestMethod("POST");
        http.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
        http.setRequestProperty("Accept-Charset", "UTF-8");
        if (params != null) {
            http.setDoOutput(true);
        }
        http.setDoInput(true);
        System.setProperty("sun.net.client.defaultConnectTimeout", "30000");// 连接超时30秒
        System.setProperty("sun.net.client.defaultReadTimeout", "30000"); // 读取超时30秒
        http.connect();
        if (params != null) {
            OutputStream os = http.getOutputStream();
            os.write(params);// 传入参数
            os.flush();
            os.close();
        }
        int responseCode = http.getResponseCode();
        if (needResult && responseCode == 200) {
            InputStream is = http.getInputStream();
            List<Byte> res = new ArrayList<>();
            int size = is.available();
            byte[] tmpBytes = new byte[size];
            int len = 0;
            while ((len = is.read(tmpBytes)) != -1) {
                for (int i = 0; i < len; i++) {
                    res.add(tmpBytes[i]);
                }
            }
            byte[] resBytes = new byte[res.size()];
            int index = 0;
            for (Byte b : res) {
                resBytes[index] = b;
                index++;
            }
            resMap.put(RESPONSE_BODY, resBytes);
        }
        resMap.put(RESPONSE_CODE, responseCode);
        return resMap;
    }
}
